<template>
  <div class="short-video-bg">
    <div class="short-video-center">
      <div class="video-player-container" v-loading="loading">
        <div v-if="error" class="error-message">
          {{ error }}
        </div>
        <div v-else-if="!currentVideo" class="empty-message">
          暂无视频数据
        </div>
        <div v-else class="video-wrapper">
          <video
            ref="videoPlayer"
            :src="currentVideo.url"
            class="video-element"
            @play="isPlaying = true"
            @pause="isPlaying = false"
            @click="togglePlay"
            @ended="handleVideoEnd"
            controls
            preload="auto"
          ></video>
        </div>
        <div class="bottom-buttons">
          <el-button class="control-btn" @click="togglePlay">
            暂停/播放
          </el-button>
          <el-button class="control-btn" @click="fetchNextVideo" :loading="loadingNext">
            换一位
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ShortVideo',
  data() {
    return {
      videos: [],
      loading: false,
      loadingNext: false,
      error: null,
      currentVideo: null,
      currentIndex: 0,
      isPlaying: false,
      isMuted: false,
      currentTime: 0,
      progressWidth: 0,
      defaultCover: 'https://via.placeholder.com/400x600',
      apiUrl: '/video-api/web.php',
      videoCount: 0,
      progressTimer: null
    }
  },
  created() {
    this.fetchVideos()
  },
  mounted() {
    this.startProgressTimer()
    // 初始化音量设置
    this.$nextTick(() => {
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.volume = 0.5  // 将音量降低到50%
      }
    })
  },
  beforeDestroy() {
    this.clearProgressTimer()
    this.releaseVideoUrls()
  },
  methods: {
    async fetchVideos() {
      this.loading = true
      this.error = null
      try {
        const response = await axios.get(this.apiUrl, {
          responseType: 'blob'
        })
        const videoUrl = URL.createObjectURL(response.data)
        
        // 创建一个视频对象
        const newVideo = {
          url: videoUrl,
          title: `短视频 ${++this.videoCount}`,
          description: '这是一个精彩的短视频',
          cover: this.defaultCover
        }
        
        // 将新视频添加到列表中
        this.videos.push(newVideo)
        
        // 设置当前视频
        if (!this.currentVideo) {
          this.currentVideo = newVideo
          this.$nextTick(() => {
            this.playCurrentVideo()
          })
        }
      } catch (err) {
        this.error = '获取视频失败，请稍后重试'
        console.error('获取视频失败:', err)
      } finally {
        this.loading = false
      }
    },
    
    async fetchNextVideo() {
      if (this.loadingNext) return
      
      this.loadingNext = true
      try {
        const response = await axios.get(this.apiUrl, {
          responseType: 'blob'
        })
        const videoUrl = URL.createObjectURL(response.data)
        
        // 创建一个新的视频对象
        const newVideo = {
          url: videoUrl,
          title: `短视频 ${++this.videoCount}`,
          description: '这是一个精彩的短视频',
          cover: this.defaultCover
        }
        
        // 将新视频添加到列表中
        this.videos.push(newVideo)
        
        // 更新当前播放的视频
        this.currentVideo = newVideo
        this.progressWidth = 0
        this.currentTime = 0
        
        // 重置视频播放器并播放新视频
        this.$nextTick(() => {
          if (this.$refs.videoPlayer) {
            this.$refs.videoPlayer.volume = 0.5  // 将音量降低到50%
          }
          this.playCurrentVideo()
        })
      } catch (err) {
        this.$message.error('获取下一个视频失败，请稍后重试')
        console.error('获取下一个视频失败:', err)
      } finally {
        this.loadingNext = false
      }
    },
    
    playCurrentVideo() {
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.currentTime = 0
        this.$refs.videoPlayer.volume = 0.5  // 将音量降低到50%
        this.$refs.videoPlayer.play().catch(err => {
          console.error('视频播放失败:', err)
          this.$message.error('视频播放失败，请稍后重试')
        })
      }
    },
    
    togglePlay() {
      const player = this.$refs.videoPlayer
      if (player) {
        if (player.paused) {
          player.play()
        } else {
          player.pause()
        }
      }
    },
    
    toggleMute() {
      const player = this.$refs.videoPlayer
      if (player) {
        player.muted = !player.muted
        this.isMuted = player.muted
      }
    },
    
    toggleFullscreen() {
      const player = this.$refs.videoPlayer
      if (!player) return
      
      if (!document.fullscreenElement) {
        player.requestFullscreen().catch(err => {
          console.error('无法进入全屏模式:', err)
        })
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        }
      }
    },
    
    handleVideoEnd() {
      this.isPlaying = false
      this.progressWidth = 100
    },
    
    startProgressTimer() {
      this.clearProgressTimer()
      this.progressTimer = setInterval(() => {
        const player = this.$refs.videoPlayer
        if (player) {
          this.currentTime = player.currentTime
          if (!player.paused && player.duration) {
            this.progressWidth = (player.currentTime / player.duration) * 100
          }
        }
      }, 100)
    },
    
    clearProgressTimer() {
      if (this.progressTimer) {
        clearInterval(this.progressTimer)
        this.progressTimer = null
      }
    },
    
    formatTime(seconds) {
      if (!seconds) return '0:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins}:${secs < 10 ? '0' + secs : secs}`
    },
    
    releaseVideoUrls() {
      // 释放所有创建的URL对象
      this.videos.forEach(video => {
        if (video.url && video.url.startsWith('blob:')) {
          URL.revokeObjectURL(video.url)
        }
      })
    }
  }
}
</script>

<style scoped>
html, body {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.short-video-bg {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #191c22 0%, #23262e 100%);
  overflow: hidden;
  position: fixed;
  left: 0;
  top: 0;
}

.short-video-center {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  /* 保证内容始终居中 */
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: visible;
}

.video-player-container {
  background: #18191f;
  border-radius: 18px;
  box-shadow: 0 0 0 2px #393c44, 0 8px 32px 0 rgba(0,0,0,0.25);
  width: 95vw;
  max-width: 420px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  min-height: 0;
  overflow: hidden;
}

.video-wrapper {
  width: 100%;
  background: #22232a;
  border-radius: 16px 16px 0 0;
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  min-height: 320px;
  max-height: 60vh;
  position: relative;
}

.video-element {
  width: 100%;
  height: 100%;
  max-height: 60vh;
  object-fit: contain;
  background: #22232a;
  border-radius: 16px 16px 0 0;
  outline: none;
  border: none;
}

.bottom-buttons {
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 18px;
  background: #18191f;
  border-radius: 0 0 16px 16px;
  padding: 24px 24px 24px 24px;
  box-sizing: border-box;
  margin-top: 0;
}

.control-btn {
  flex: 1;
  font-size: 18px;
  font-weight: 500;
  color: #fff;
  background: #23242a;
  border: none;
  border-radius: 10px;
  height: 48px;
  margin: 0;
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.10);
  letter-spacing: 1px;
}

.control-btn:hover,
.control-btn:focus {
  background: #2e3038;
  color: #fff;
}

.error-message,
.empty-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 16px;
  text-align: center;
  background: rgba(0,0,0,0.7);
  padding: 20px 32px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  z-index: 10;
}

@media (max-width: 600px) {
  .video-player-container {
    max-width: 100vw;
    border-radius: 0;
    box-shadow: none;
  }
  .video-wrapper {
    border-radius: 0;
    min-height: 220px;
    max-height: 40vh;
  }
  .bottom-buttons {
    border-radius: 0 0 12px 12px;
    padding: 16px 8px;
    gap: 10px;
  }
  .control-btn {
    font-size: 16px;
    height: 40px;
    border-radius: 8px;
  }
}
</style>